package se.energimyndigheten.lampguiden.bulbreplacement;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.TextView;

import org.json.JSONException;

import se.energimyndigheten.lampguiden.R;
import se.energimyndigheten.lampguiden.DashboardActivity;
import se.energimyndigheten.lampguiden.LightSource;
import se.energimyndigheten.lampguiden.SubPageActivity;
import se.energimyndigheten.lampguiden.bulbreplacement.SetPriceDialogFragment.onPriceChangedListener;
import se.energimyndigheten.lampguiden.util.AssetsUtil;

import java.io.IOException;
import java.util.Map;

public class ResultActivity extends SubPageActivity  implements onPriceChangedListener {
    private static final String TAG = ResultActivity.class.getSimpleName();
    private static final String HELP_PATH = DashboardActivity.HTML_BASEPATH + "Help/sv_ResultList.html";
    private static final String EXPLAIN_PATH = DashboardActivity.HTML_BASEPATH + "sv_Sa_har_vi_raknat.html";

    private LightSource mLight;
    private SetPriceDialogFragment mDialog;
    private ResultListFragment mFrag;
    private Map<Integer, String> mConversionTable;
    private ComparsionCalculator cc;
    private String lumen = "";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getSupportActionBar().setIcon(R.drawable.ic_actionbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        setContentView(R.layout.result_activity);

        prepareCalculations();
        // update title label
        ((TextView) findViewById(android.R.id.text2)).setText(getResources().getString(
                R.string.power_lumen_label,
                lumen));
        mFrag = ResultListFragment.newInstance();
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.add(R.id.fragment_container, mFrag);
        ft.setTransition(FragmentTransaction.TRANSIT_NONE);
        ft.commit();
    }
    
    private void prepareCalculations() {
        // get light from intent
        // grab socket type from intent and parse lightsource from json
        int socket = -1;
        int powerIndex = -1;

        try {
            socket = getIntent().getIntExtra(SocketActivity.KEY_SOCKET, -1);
            powerIndex = getIntent().getIntExtra(PowerActivity.KEY_POWER, -1);
            String json = AssetsUtil.getFileContents(getAssets(), AssetsUtil.JSON_PATH_LIGHTSOURCE);
            mLight = AssetsUtil.getLightSourceFromJson(json, socket);
            mConversionTable = AssetsUtil.getConversionTableFromJson(json, mLight.getLampType());
            lumen = mConversionTable.get(powerIndex);
            lumen = lumen.replace(",", " - ");
        } catch (NullPointerException npE) {
            Log.e(TAG, "Invalid or missing intent. Expected intent with string extra: " + SocketActivity.KEY_SOCKET);
            socket = -1;
        } catch (JSONException jsonE) {
            Log.e(TAG, "JSONException parsing JSON to LightSource");
            jsonE.printStackTrace();
            socket = -1;
        } catch (IOException ioE) {
            Log.e(TAG, "IOException reading JSON");
            ioE.printStackTrace();
            socket = -1;
        } finally {
            if (socket == -1 && powerIndex == -1) {
                // fail - bail
                finish();
                return;
            }
        }

        // initiate comparsion calculator
        cc = null;
        try {
            cc = ComparsionCalculator.initiateCalculator(this, mLight, powerIndex, mConversionTable);
        } catch (JSONException e) {
            Log.e(TAG, "JSONException reading calculation data.");
            e.printStackTrace();
        } catch (IOException e) {
            Log.e(TAG, "IOException reading calculation file.");
            e.printStackTrace();
        } finally {
            if (cc == null) {
                // fail - bail
                finish();
                return;
            }
        }
    }

    @Override
    protected void onResume() {
        mSelectedActivity = ACTIVITY_SOCKET;
        super.showHelpActionItem(HELP_PATH);
        super.onResume();
    }    
    
    // The light currently being changed in the dialog
    LightSource light = null;
    
    /** xml event handler (from ResultListFragment) */
    public void onItemSelected(View view) {
        Log.v(TAG, "onItemSelected");
        mFrag.handleItemSelection((View) view.getParent());
    }

    
    /** xml event handler (from ResultListFragment) */
    public void onChangePrice(View view) {
        Log.v(TAG, "onChangePrice");
        light = (LightSource) view.getTag();
        showEditDialog(light);
    }

    /** xml event handler (from ResultListFragment) */
    public void onReadFormula(View view) {
        Intent intent = new Intent(this, ExplainActivity.class);
        intent.putExtra(ExplainActivity.EXTRA_HTML_PATH, EXPLAIN_PATH);
        startActivity(intent);
    }

    private void showEditDialog(LightSource light) {
        FragmentManager fm = getSupportFragmentManager();
        mDialog =  SetPriceDialogFragment.newInstance(light.getMyPrice(), light.getYears());
        mDialog.show(fm, "fragment_edit_name");
    }

    @Override
    public void onPriceChanged(int price) {
        mDialog.dismiss();
        if (light!=null) {
            light.setMyPrice(price);
            cc.savePrice(price, light);
        }
        if (mFrag!=null) {
            ((BaseAdapter)mFrag.getListView().getAdapter()).notifyDataSetChanged();
        }
    }

    @Override
    public int calculateSavings(LightSource light, int price) {
        return cc.getCostComparsion(light, price);
    }

    @Override
    public int calculateSavings(int price) {
        if (light==null)
            return 0;
        return cc.getCostComparsion(light, price);
    }

    @Override
    public LightSource[] getLightSources() {
        if (cc==null)
            prepareCalculations();
        if (cc==null)
            return null;
        return cc.getLightSources();
    }
}
